let isLoading = false;

/**
 * 整合封装微信的原生弹窗
 * 提示、加载、工具类
 */
const Tips = {
  /**
   * 提示信息
   */
  toast: (title: string, mask = false, onHide?: () => void) => {
    uni.showToast({
      title,
      icon: "none",
      mask,
      duration: 3500,
    });
    // 去除结束回调函数
    if (onHide) {
      setTimeout(() => {
        onHide();
      }, 500);
    }
  },

  /**
   * 加载提示弹窗
   */
  loading: (title = "加载中", force = false) => {
    if (isLoading && !force) {
      return;
    }
    isLoading = true;
    if (uni.showLoading) {
      uni.showLoading({
        title,
        mask: true,
      });
    } else {
      uni.showNavigationBarLoading(); // 导航条加载动画
    }
  },

  /**
   * 加载完成
   */
  loadEnd: () => {
    if (isLoading) {
      isLoading = false;
      if (uni.hideLoading) {
        uni.hideLoading();
      } else {
        uni.hideNavigationBarLoading(); // 导航条加载动画
      }
    }
  },

  /**
   * 加载完成
   */
  loadEndPro: async () => {
    let duration = 0;
    if (isLoading) {
      isLoading = false;
      if (uni.hideLoading) {
        uni.hideLoading();
      } else {
        uni.hideNavigationBarLoading(); // 导航条加载动画
      }
      duration = 500;
    }
    // 设定隐藏的动画时长为500ms,防止直接toast时出现问题
    return await new Promise((resolve) => setTimeout(resolve, duration));
  },

  /**
   * 弹出提示框
   */
  success: async (title: string, duration = 1500) => {
    uni.showToast({
      title,
      icon: "success",
      duration,
      mask: true,
    });
    if (duration > 0) {
      return await new Promise((resolve) => setTimeout(resolve, duration));
    }
  },
};

export default Tips;
